package com.hlf.modules.sys.controller;

import com.hlf.common.annotation.SysLog;
import com.hlf.common.constants.Constants;
import com.hlf.common.utils.Constant;
import com.hlf.common.utils.PageUtils;
import com.hlf.common.utils.Query;
import com.hlf.common.utils.ReturnResult;
import com.hlf.common.validator.Assert;
import com.hlf.common.validator.ValidatorUtils;
import com.hlf.common.validator.group.AddGroup;
import com.hlf.common.validator.group.UpdateGroup;
import com.hlf.modules.sys.entity.SysUserEntity;
import com.hlf.modules.sys.service.SysUserRoleService;
import com.hlf.modules.sys.service.SysUserService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月31日 上午10:40:10
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 所有用户列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:user:list")
    public ReturnResult list(@RequestParam Map<String, Object> params){
        //只有超级管理员，才能查看所有管理员列表
        if(getUserId() != Constant.SUPER_ADMIN){
            params.put("createUserId", getUserId());
        }

        //查询列表数据
        Query query = new Query(params);
        List<SysUserEntity> userList = sysUserService.queryList(query);
        int total = sysUserService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());

        return ReturnResult.ok().put("page", pageUtil);
    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping("/info")
    public ReturnResult info(){
        return ReturnResult.ok().put("user", getUser());
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @RequestMapping("/password")
    public ReturnResult password(String password, String newPassword){
        Assert.isBlank(newPassword, "新密码不为能空");

        //sha256加密
        password = new Sha256Hash(password, getUser().getSalt()).toHex();
        //sha256加密
        newPassword = new Sha256Hash(newPassword, getUser().getSalt()).toHex();

        //更新密码
        int count = sysUserService.updatePassword(getUserId(), password, newPassword);
        if(count == 0){
            return ReturnResult.error("原密码不正确");
        }

        return ReturnResult.ok();
    }

    /**
     * 用户信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public ReturnResult info(@PathVariable("userId") Long userId){
        SysUserEntity user = sysUserService.queryObject(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);

        return ReturnResult.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @RequestMapping("/save")
    @RequiresPermissions("sys:user:save")
    public ReturnResult save(@RequestBody SysUserEntity user){
        ValidatorUtils.validateEntity(user, AddGroup.class);

        user.setCreateUserId(getUserId());
        sysUserService.save(user);

        return ReturnResult.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @RequestMapping("/update")
    @RequiresPermissions("sys:user:update")
    public ReturnResult update(@RequestBody SysUserEntity user){
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        user.setCreateUserId(getUserId());
        sysUserService.update(user);

        return ReturnResult.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public ReturnResult delete(@RequestBody Long[] userIds){
        if(ArrayUtils.contains(userIds, 1L)){
            return ReturnResult.error("系统管理员不能删除");
        }

        if(ArrayUtils.contains(userIds, getUserId())){
            return ReturnResult.error("当前用户不能删除");
        }

        sysUserService.deleteBatch(userIds);

        return ReturnResult.ok();
    }

    /**
     * 管理员列表
     */
    @RequestMapping("manager")
    public ReturnResult manager(@RequestParam Map<String, Object> params) {
        SysUserEntity user = getUser();
        params.put("userId",user.getUserId());
        params.put("storeId",user.getCurrentStoreId());
        return sysUserService.managerList(params);
    }

    /**
     * 新建管理员
     */
    @SysLog("新建管理员")
    @PostMapping("createM")
    public ReturnResult register(@RequestBody Map<String,String> map) {
        String mobile = map.get("username");
        String name = map.get("name");
        String password = map.get("password");
        String identifyCode = map.get("identifyCode");
        String auth = map.get("auth");
        String merchantCode = map.get("merchantCode");
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(name, "昵称不能为空");
        Assert.isBlank(password, "密码不能为空");
        Assert.isBlank(identifyCode, "验证码不能为空");
        Assert.isBlank(auth, "权限类型不能为空");
        if (String.valueOf(Constants.ROLE_ID_STOREADMIN).equals(auth)) {
            Assert.isBlank(merchantCode, "商家验证码不能为空!");
        }
        SysUserEntity user = getUser();

        if (user.getUserId() == 1){
            return ReturnResult.error("系统管理员不能创建门店管理员!");
        }
        sysUserService.saveManager(mobile, password, name, identifyCode, merchantCode, auth, user);
        return ReturnResult.ok();
    }

    /**
     * 解绑管理员
     */
    @SysLog("解绑管理员")
    @RequestMapping("freeManager")
    public ReturnResult manager(@RequestBody String[] userNames) {
        Assert.isNull(userNames,"用户id不能为空!");

        SysUserEntity user = getUser();
        for (String s : userNames) {
            sysUserService.freeManager(user,s);
        }
        return ReturnResult.ok();
    }







}
